use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::attribute_group_translations::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub attribute_group_id: String,
    pub locale: String,
    pub name: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Attribute Group ID must not be empty."))]
    pub attribute_group_id: String,
    #[validate(length(min = 1, message = "Locale must not be empty."))]
    pub locale: String,
    #[validate(length(min = 1, message = "Name must not be empty."))]
    pub name: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            attribute_group_id: self.attribute_group_id.as_ref().to_owned(),
            locale: self.locale.as_ref().to_owned(),
            name: self.name.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds an attribute group translation by the provided id
    ///
    /// # Errors
    ///
    /// When could not find attribute group translation or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let translation = attribute_group_translations::Entity::find()
            .filter(
                model::query::condition()
                    .eq(attribute_group_translations::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        translation.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds attribute group translations by the provided attribute_group_id
    ///
    /// # Errors
    ///
    /// When could not find attribute group translations or DB query error
    pub async fn find_by_attribute_group_id(
        db: &DatabaseConnection,
        attribute_group_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let translations = attribute_group_translations::Entity::find()
            .filter(
                query::condition()
                    .eq(
                        attribute_group_translations::Column::AttributeGroupId,
                        attribute_group_id,
                    )
                    .build(),
            )
            .all(db)
            .await?;
        Ok(translations)
    }


    pub async fn find_by_locale(
        db: &DatabaseConnection,
        locale: &str,
    ) -> ModelResult<Vec<Self>> {
        let translations = attribute_group_translations::Entity::find()
            .filter(
                query::condition()
                    .eq(
                        attribute_group_translations::Column::Locale,
                        locale,
                    )
                    .build(),
            )
            .all(db)
            .await?;
        Ok(translations)
    }

    /// Asynchronously creates an attribute group translation and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the attribute group translation into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let txn = db.begin().await?;

        let translation = ActiveModel {
            attribute_group_id: ActiveValue::set(params.attribute_group_id.to_string()),
            locale: ActiveValue::set(params.locale.to_string()),
            name: ActiveValue::set(params.name.to_string()),
            ..Default::default()
        }
        .insert(&txn)
        .await?;

        txn.commit().await?;

        Ok(translation)
    }
}

impl ActiveModel {
    pub async fn update_name(
        mut self,
        db: &DatabaseConnection,
        name: String,
    ) -> ModelResult<Model> {
        self.name = ActiveValue::set(name);
        Ok(self.update(db).await?)
    }
}